<?php

namespace App\Services\Draw\DrawObject;

use App\Exceptions\BasicException;
use App\Jobs\QiPao\Draw\FragDrawStatisticsJob;
use App\Models\MainDB\GiftBackpack;
use App\Repositories\GiftRepository;
use App\Repositories\Frag\FragPropsRepository;
use App\Services\Draw\Enum\DrawEnum;
use App\Services\Draw\PoolGroupObject\FragIndependentPoolGroup;
use App\Services\Draw\PoolGroupObject\FragPublicPoolGroup;
use App\Services\Tools\PushChatService;
use App\Services\Tools\PushService;
use App\Services\Tools\RedisService;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class Frag extends Draw
{
    protected $isDrawCriticalGift = false;
    protected $cachePrefix = 'frag:';
    protected $privateKey = 'frag';
    protected $balanceNotEnoughMsg = '召唤令不足';
    protected $drawLockKey = "draw:frag:lock_";
    protected $isDrawAccumulate = false; //是否做抽奖计数累计逻辑
    protected $game_name = '仙气';

    protected $isFragment   = 1;

    public function __construct()
    {
        parent::__construct();
        $this->redisObject               = app('redis')->connection('game');
        $this->poolConfigModel           = app('model_frag_pool_config');
        $this->poolUserModel             = app('model_frag_pool_user');
        $this->poolModel                 = app('model_frag_pool');
        $this->poolPrizeModel            = app('model_frag_pool_prize');
        $this->poolGroupModel            = app('model_frag_pool_group');
        $this->giftTemplateModel         = app('model_frag_gift_template');
        $this->poolTemplateModel         = app('model_frag_pool_template');
        $this->poolDrawModel             = app('model_frag_pool_draw');
        $this->poolDrawRecordModel       = app('model_frag_pool_draw_record');
        $this->poolIndependentModel      = app('model_frag_pool_independent');
        $this->poolIndependentPrizeModel = app('model_frag_pool_independent_prize');
        $this->appointGiftModel          = app('model_frag_appoint_gift');
        $this->fragmentGroupModel        = app('model_frag_fragment_group');
        $this->fragmentUserRecordModel   = app('model_frag_fragment_user_record');
        $this->fragmentPoolRecordModel   = new \App\Models\GameDB\Frag\FragmentPoolRecord();
        $this->fragmentPoolModel         = new \App\Models\GameDB\Frag\FragmentPool();

        $this->checkRecordModel = app('model_frag_draw_check_record');
        $this->addPoolAccountRecordModel = app('model_frag_draw_add_pool_account_record');
        $this->addPoolRepo = app('repo_add_pool_frag');

        $this->independentPoolGroup = new FragIndependentPoolGroup($this->redisObject);
        $this->publicPoolGroup      = new FragPublicPoolGroup($this->redisObject);
    }

    public function isNovice($user, $poolConfig)
    {
        return $user->input_week <= $poolConfig->novice_coin;
    }

    // 添加抽奖记录
    public function addDrawRecord($user, $poolGroup, array $drawIOPut, Collection $gifts, $criticalGift, array $drawPrizes, int $drawCount, int $drawPrizesCount)
    {
        //并发处理
        if ($poolGroup->group_id == 0) {
            $poolGroup->group_id = key($drawPrizes);
        }


        $drawData = [
            "user_id"    => $user->user_id,
            "group_id"   => $poolGroup->group_id,
            "tag"        => $poolGroup->tag,
            "count"      => $drawCount,
            "gift_count" => $drawPrizesCount,
            "input"      => $drawIOPut['input'],
            "output"     => $drawIOPut['output'],
        ];

        $poolDrawId = $this->poolDrawModel->createDataGetId($drawData);
        if (empty($poolDrawId)) {
            throw new BasicException(-1, '抽奖记录保存错误');
        }
        $drawPrizesRecord = [];
        foreach ($drawPrizes as $groupId => $groupPrize) {
            foreach ($groupPrize as $prizeId => $prizeCount) {
                $gift   = $gifts->where('gift_template_id', $prizeId)->first();
                $drawPrizesRecord[] = [
                    'user_id' => $user->user_id,
                    'draw_id' => $poolDrawId,
                    'group_id' => $groupId,
                    'gift_id' => $gift->id,
                    'gift_price' => $gift->price,
                    'count' => $prizeCount,
                    'gift_type' => $gift->type
                ];
            }
        }
        if (!empty($criticalGift)) {
            $drawPrizesRecord[] = [
                'user_id' => $user->user_id,
                'draw_id' => $poolDrawId,
                'group_id' => 0,
                'gift_id' => $criticalGift['id'],
                'gift_price' => 0,
                'count' => $criticalGift['count'],
                'gift_type' => DrawEnum::PROP_GIFT_TYPE
            ];
        }

        $this->poolDrawRecordModel->insert($drawPrizesRecord);
        return $drawData;
    }

    public function getDrawJob($poolGroup, $user, $jobData)
    {
        return new FragDrawStatisticsJob($poolGroup, $user, $jobData, $this->cachePrefix);

    }

    public function getGiftList(array $drawPrizes)
    {
        //根据模板礼物ID获取礼物ID
        $templateGiftIds = [];
        $giftPrizes      = [];
        foreach ($drawPrizes as $groupId => $groupPrize) {
            foreach ($groupPrize as $prizeId => $prizeCount) {
                $templateGiftIds[] = $prizeId;
                if (isset($giftPrizes[$prizeId])) {
                    $giftPrizes[$prizeId] += $prizeCount;
                } else {
                    $giftPrizes[$prizeId] = $prizeCount;
                }
            }
        }

        $templateGiftList   = $this->giftTemplateModel->getGiftListByIds($templateGiftIds, ['id', 'type', 'gift_id']);
        $templateGiftWithId = $templateGiftList->where('type', DrawEnum::NORMAL_GIFT_TYPE)->KeyBy('gift_id');
        //$templatePropWithId = $templateGiftList->where('type', DrawEnum::PROP_GIFT_TYPE)->KeyBy('gift_id');
        $giftInfoList = (new GiftRepository())->giftsByIds($templateGiftWithId->keys()); // 抽中礼物信息

        foreach ($giftInfoList as $giftInfo) {
            $giftInfo->gift_template_id = $templateGiftWithId[$giftInfo['id']] ? $templateGiftWithId[$giftInfo['id']]['id'] : 0;
            $giftInfo->count            = $giftPrizes[$giftInfo->gift_template_id] ?? 0;
            $giftInfo->type             = DrawEnum::NORMAL_GIFT_TYPE;
        }

//        if (!empty($templatePropWithId)) {
//            //查询道具价格
//            $propGiftList = app('model_props')->select('id', 'name', 'prope_icon as picture', 'price')->whereIn('id', $templatePropWithId->keys())->where('is_delete', 0)->get();
//            if ($propGiftList->isNotEmpty()) {
//                $propGiftListWithId = $propGiftList->KeyBy('id');
//                foreach ($templatePropWithId as $templateId => $propGift) {
//                    $propGiftInfo                   = $propGiftListWithId[$propGift['gift_id']];
//                    $propGiftInfo->gift_template_id = $propGift->id;
//                    $propGiftInfo->count            = $giftPrizes[$propGift->id] ?? 0;
//                    $propGiftInfo->type             = DrawEnum::PROP_GIFT_TYPE;
//                    $giftInfoList[]                 = $propGiftInfo;
//                }
//            }
//        }

        return $giftInfoList;
    }

    public function getNotifyGiftList($count)
    {
        $cacheNotifyRecordList = $this->redisObject->get($this->cachePrefix . "notifyRecordList:" . $count);
        if (!empty($cacheNotifyRecordList)) {
            $notifyRecordList = json_decode($cacheNotifyRecordList, true);
        }
        if (empty($notifyRecordList)) {
            $notifyRecordList = parent::getNotifyGiftList($count);
            $this->redisObject->setex($this->cachePrefix . "notifyRecordList:" . $count, 60, json_encode($notifyRecordList));
        }

        return $notifyRecordList;
    }


//    public function pushv1($user, array $notifyPushData, array $broadcastPushData, array $extraPushData)
//    {
//        try {
//            $userChatLabel = RedisService::getUserChatLabel($user->user_id);
//            //$levelInfo = $this->levelModel->one(['level' => $user->level]);
//
//            foreach ($notifyPushData as $value) {
//                // (new PushChatService())->lotteryStellarNew($userChatLabel, $value);
//            }
//
//
//            foreach ($notifyPushData as $value) {
//                (new PushChatService())->lotteryStellarNew($userChatLabel, $value);
//            }
//
//            (new PushService())->lotteryStellar($broadcastPushData, $userChatLabel);
//        } catch (\Exception $e) {
//            return false;
//        }
//        return true;
//    }

    /**
     * @param $user
     * @param array $notifyPushData
     * @param array $broadcastPushData
     * @param array $extraPushData
     * @throws \Exception
     */
    public function push($user, array $notifyPushData, array $broadcastPushData, array $extraPushData)
    {
        $userChatLabel = RedisService::getUserChatLabel($user->user_id);
        $uni_key = uniqidReal();
        $getMillisecond = getMillisecond();
        $PushService = new PushService();
        // /幸运票品
        $notifyPush = [];
        if(!empty($notifyPushData)){
            $ext_data = $userChatLabel;
            #$txt = "<font color='#FFD39B'>".$userChatLabel['nickname']." </font>";
            $txt    = "<font color='#FAFAFA'>在魔兽争霸中意外获得 </font>";
            $sort_k = 0;
            foreach ($notifyPushData as $key => $value) {
                $sort_k ++;
                $txt .= '<font color="#FFD39B">'.$value->price.'金币</font>';
                $txt .= '<font color="#FAFAFA">的</font>';
                $txt .= '<font color="#FF83FA">'.$value->name.'x'.$value->count.($sort_k == count($notifyPushData) ? "" : "、").'</font>';
            }
            $txt .= "<font color='#FAFAFA'>，运气爆棚！</font>";

            $ext_data['type'] = PushService::GAME_PUSH_STATUS;
            $ext_data['action'] = 1;
            $ext_data['show_area'] = [
                PushChatService::AREA_LUCKY,
                PushChatService::AREA_ALL,
            ];
            $ext_data['show_label_id'] = [
                PushChatService::AREA_LUCKY,
            ];
            $ext_data['bg_type'] = $this->privateKey;
            $notifyPush = [
                'content' => $txt,
                'uni_key' => $uni_key,
                'extra' => $ext_data,
            ];
        }
        $broadcastPush = [];
        if(!empty($broadcastPushData)){
            $txt = "<font color='#FD8469'>" . mb_substr($userChatLabel['nickname'], 0, 1) . "**</font><font color='#FFFFFF'> 在魔兽争霸获得了价值 </font>";
            $txt_extra = [];
            foreach ($broadcastPushData as $gift) {
                $txt_extra [] = [
                    'text' => $txt . "<font color='#F783FF'>" . $gift->price . "金币的</font>" . "<font color='#FABA5C'>" . $gift->name . "</font><font color='#FFFFFF'>X" . $gift->count . "</font>",
                    'picture' => $gift->picture,
                ];
            }
            $broadcastPush = [
                'uni_key' => $uni_key,
                'time' => $getMillisecond,
                'msg'  => $txt_extra,
                'bg_type' => $this->privateKey,
                'show_grade' => $this->showBroadcastGrade(),
            ];
        }

        $PushService->publicGamePush($notifyPush,$broadcastPush,[],[],$uni_key,$getMillisecond);

    }

    public function getUserQueuePool($userId, int $count)
    {
        return null;

    }

//    public function getUserPool()
//    {
//
//    }

//
//    /**
//     * @param int $userId
//     * @param int $count
//     */
//    public function swap(int $userId, int $count)
//    {
//
//    }

    public function dealFragment2($user, int $drawCount, array $poolConfig, array $gifts)
    {
        #获取特殊礼物
        $specialGiftList    = $this->giftTemplateModel->where(['is_special' => 1])->orderBy('id', "ASC")->get();
        if(empty($specialGiftList) || count($specialGiftList) != 3) {
            $logObj = new \App\Repositories\LogRepository("deal_fragment");
            $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', "user_id: ".$user['user_id']." {$drawCount}抽,未配置特殊礼物或者配置特殊礼物（nums：".count($specialGiftList)."）不等于3，不予记录碎片！");
            $logObj->File();
            return ['code' => 2, 'data' => [], 'message' => "配置异常，不予计算"];
        }
        $min_special_id = $specialGiftList[0]['id'];
        $mid_special_id = $specialGiftList[1]['id'];
        $max_special_id = $specialGiftList[2]['id'];

        $fragment_exchange_ratio    = $poolConfig['fragment_exchange_ratio'];
        $fragment_share_ratio       = $poolConfig['fragment_share_ratio'];
        $fragment_max_share         = $poolConfig['fragment_max_share'];

        $user_special_min   = $user['special_min'];
        $user_special_mid   = $user['special_mid'];
        $user_special_max   = $user['special_max'];
        $user_fragment_num  = $user['fragment_num'];

        #计算碎片池数量
        $now_add_num        = $fragment_exchange_ratio * $drawCount;
        $fragmentPoolModel  = $this->fragmentPoolModel;
        $fragmentPoolInfo   = $fragmentPoolModel::query()->lockForUpdate()->find(1);
        $now_all_num        = $fragmentPoolInfo->nums + $now_add_num;

        #判断是否存在特殊礼物
        $userUpData         = [];
        $now_special_min    = 0;
        $now_special_mid    = 0;
        $now_special_max    = 0;
        $now_count_special  = 0;
        foreach ($gifts as $gift) {
            if($gift['gift_template_id'] == $min_special_id) {
                $now_count_special ++;
                $now_special_min    = $gift['count'];
                $user_special_min += $gift['count'];
                $userUpData += ['special_min' => DB::raw('special_min +' . $gift['count'])];
            }
            if($gift['gift_template_id'] == $mid_special_id) {
                $now_count_special ++;
                $now_special_mid    = $gift['count'];
                $user_special_mid += $gift['count'];
                $userUpData += ['special_mid' => DB::raw('special_mid +' . $gift['count'])];
            }
            if($gift['gift_template_id'] == $max_special_id) {
                $now_count_special ++;
                $now_special_max    = $gift['count'];
                $user_special_max += $gift['count'];
                $userUpData += ['special_max' => DB::raw('special_max +' . $gift['count'])];
            }
        }

        #若用户集齐所有特殊礼物，则瓜分碎片
        $now_fragment_num       = 0;
        if($user_special_min > 0 && $user_special_mid > 0 && $user_special_max > 0) {
            $now_fragment_num   = floor($now_all_num * ($fragment_share_ratio / 100));#向下取整数
            $now_fragment_num   = ($now_fragment_num > $fragment_max_share ? $fragment_max_share : $now_fragment_num);
            $userUpData += ['fragment_num' => DB::raw('fragment_num +' . $now_fragment_num)];
        }
        #更新用户信息
        $userUpRes  = $this->poolUserModel->updateData(['user_id' => $user['user_id']], $userUpData);
        if(!$userUpRes && ($now_fragment_num > 0 || $now_count_special > 0)) {
            $logObj = new \App\Repositories\LogRepository("deal_fragment");
            $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'userUpData' => $userUpData, 'msg' => "用户碎片数据更新失败"]);
            $logObj->File();
            return ['code' => -1, 'data' => [], 'message' => "用户碎片数据更新失败！"];
        }

        #保存用户特殊礼物变动记录
        if($now_special_min > 0 || $now_special_mid > 0 || $now_special_max > 0) {
            $userSpecialRecordRes   = \App\Models\GameDB\Frag\FragmentUserSpecialRecord::query()->insert([
                'user_id'           => $user['user_id'],
                'special_min_num'   => $now_special_min,
                'min_num_before'    => $user['special_min'],
                'min_num_after'     => $user['special_min'] + $now_special_min,
                'special_mid_num'   => $now_special_mid,
                'mid_num_before'    => $user['special_mid'],
                'mid_num_after'     => $user['special_mid'] + $now_special_mid,
                'special_max_num'   => $now_special_max,
                'max_num_before'    => $user['special_max'],
                'max_num_after'     => $user['special_max'] + $now_special_max,
            ]);
            if(!$userSpecialRecordRes) {
                $logObj = new \App\Repositories\LogRepository("deal_fragment");
                $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'special_min_num' => $now_special_min, 'special_mid_num' => $now_special_mid, 'special_max_num' => $now_special_max, 'msg' => "用户特殊礼物数据更新失败1"]);
                $logObj->File();
                return ['code' => -1, 'data' => [], 'message' => "用户特殊礼物数据更新失败！"];
            }
        }

        #保存用户碎片获取记录,并且清空用户特殊礼物数量，重新开始计算
        $userRecordInsertId = -1;
        if($now_fragment_num > 0) {
            $userRecordData = [
                'user_id'       => $user['user_id'],
                'change_num'    => $now_fragment_num,
                'num_before'    => $user_fragment_num,
                'num_after'     => $user_fragment_num + $now_fragment_num,
                'desc'          => "集齐天使圆环，瓜分碎片：min=".($user['special_min'] + $now_special_min)." mid=".($user['special_mid'] + $now_special_mid)." max=".($user['special_max'] + $now_special_max)
            ];
            try {
                $userRecordInsertId = \App\Models\GameDB\Frag\FragmentUserRecord::query()->insertGetId($userRecordData);
            }catch (\Exception $e) {
                $userRecordInsertId = -1;
            }
            if(empty($userRecordInsertId)  || $userRecordInsertId == -1) {
                $logObj = new \App\Repositories\LogRepository("deal_fragment");
                $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'msg' => "用户碎片数据记录失败"]);
                $logObj->File();
                return ['code' => -1, 'data' => [], 'message' => "用户碎片数据记录失败！"];
            }
            #清空用户特殊礼物数量
            $userUpSpecialRes   = $this->poolUserModel->updateData(['user_id' => $user['user_id']], ['special_min' => 0, 'special_mid' => 0, 'special_max' => 0]);
            if(!$userUpSpecialRes) {
                $logObj = new \App\Repositories\LogRepository("deal_fragment");
                $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'special_min' => $user_special_min, 'special_mid' => $user_special_mid, 'special_max' => $user_special_max, 'msg' => "用户特殊礼物数量更新失败"]);
                $logObj->File();
                return ['code' => -1, 'data' => [], 'message' => "用户特殊礼物数量更新失败！"];
            }
            #记录特殊礼物变动记录
            $userSpecialRecordRes   = \App\Models\GameDB\Frag\FragmentUserSpecialRecord::query()->insert([
                'user_id'           => $user['user_id'],
                'special_min_num'   => -$user_special_min,
                'min_num_before'    => $user_special_min,
                'min_num_after'     => 0,
                'special_mid_num'   => -$user_special_mid,
                'mid_num_before'    => $user_special_mid,
                'mid_num_after'     => 0,
                'special_max_num'   => -$user_special_max,
                'max_num_before'    => $user_special_max,
                'max_num_after'     => 0,
            ]);
            if(!$userSpecialRecordRes) {
                $logObj = new \App\Repositories\LogRepository("deal_fragment");
                $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'special_min_num' => $now_special_min, 'special_mid_num' => $now_special_mid, 'special_max_num' => $now_special_max, 'msg' => "用户碎片数据减少记录失败"]);
                $logObj->File();
                return ['code' => -1, 'data' => [], 'message' => "用户碎片数据减少记录失败！"];
            }
        }

        #更新碎片池数据
        $upFragmentPoolRes  = $fragmentPoolModel::query()->where(['id' => 1])->update(['nums' => $now_all_num - $now_fragment_num]);
        if(!$upFragmentPoolRes) {
            $logObj = new \App\Repositories\LogRepository("deal_fragment");
            $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'change_num' => $now_add_num - $now_fragment_num, 'num_before' => $fragmentPoolInfo->nums, 'num_after' => $now_all_num - $now_fragment_num, 'msg' => "碎片池数据更新失败"]);
            $logObj->File();
            return ['code' => -1, 'data' => [], 'message' => "碎片池数据更新失败！"];
        }

        #保存碎片池记录
        $poolRecordData     = [];
        $poolRecordData[]   = [
            'relation_id'   => 0,
            'change_num'    => $now_add_num,
            'num_before'    => $fragmentPoolInfo->nums,
            'num_after'     => $now_all_num
        ];
        if($now_fragment_num > 0) {
            $poolRecordData[]   = [
                'relation_id'   => $userRecordInsertId,
                'change_num'    => -$now_fragment_num,
                'num_before'    => $now_all_num,
                'num_after'     => $now_all_num - $now_fragment_num
            ];
        }
        $poolRecordInsertRes    = $this->fragmentPoolRecordModel::query()->insert($poolRecordData);
        if(!$poolRecordInsertRes) {
            $logObj = new \App\Repositories\LogRepository("deal_fragment");
            $logObj->log('deal_fragment['.date("Y-m-d H:i:s").']', ['user_id' => $user['user_id'], 'draw_count' => $drawCount, 'now_fragment_num' => $now_fragment_num, 'now_all_num' => $now_all_num, 'msg' => "碎片池数据记录失败"]);
            $logObj->File();
            return ['code' => -1, 'data' => [], 'message' => "碎片池数据记录失败！"];
        }

        return [
            'code'      => 1,
            'data'      => [
                'fragment_num'  => [
                    'num'       => $now_fragment_num,
                    'before'    => $user_fragment_num,
                    'after'     => $user_fragment_num + $now_fragment_num
                ],
                'special_min'   => [
                    'num'       => $now_special_min,
                    'before'    => $user['special_min'],
                    'after'     => $user_special_min
                ],
                'special_mid'   => [
                    'num'       => $now_special_mid,
                    'before'    => $user['special_mid'],
                    'after'     => $user_special_mid
                ],
                'special_max'   => [
                    'num'       => $now_special_max,
                    'before'    => $user['special_max'],
                    'after'     => $user_special_max
                ],
                'special_count' => $now_count_special
            ],
            'message'   => 'ok'
        ];
    }

    public function dealFragment($user, int $drawCount, array $poolConfig, array $gifts, array $extra = [])
    {
        /*$cursor = 0;
        [$cursor, $keys] = $this->redisObject->scan($cursor, ['MATCH' => $this->cachePrefix.'fragment:*', 'COUNT' => 100]);
        $this->redisObject->del($keys);
        die;*/

        $fragment_group = RedisService::getDrawFragmentGroup($this->cachePrefix, $this->fragmentGroupModel, $this->giftTemplateModel);
        if (empty($fragment_group)) {
            throw new BasicException(-1, '---碎片组合配置异常---');
        }
        $is_all = 0;
//        $all_gift_template_ids = array_merge(...array_column($fragment_group, 'gift_template_ids'));
        $fragmentPoolModel  = $this->fragmentPoolModel;
        $fragmentPoolInfo   = $fragmentPoolModel::query()->lockForUpdate()->find(1);
        if (empty($fragmentPoolInfo) || empty($poolConfig['send_gift_id'])) {
            throw new BasicException(-1, '--碎片配置异常--');
        }
        $fragment_exchange_ratio    = $poolConfig['fragment_exchange_ratio'];//碎片产生的比例
        $fragment_max_share         = $poolConfig['fragment_max_share'];//碎片最大分成数量
        #计算碎片池数量
        $fragment_pool_num_key = $this->cachePrefix."fragment_pool:nums";
        $now_add_num       = floor($fragment_exchange_ratio * $drawCount * $poolConfig['balance_coin'] / 100);
        $now_num           = $this->redisObject->get($fragment_pool_num_key);
        $pool_num = $this->redisObject->incrby($fragment_pool_num_key, $now_add_num);
        $poolRecordData[]   = [
            'relation_id'   => 0,
            'change_num'    => $now_add_num,
            'num_before'    => $now_num,
            'num_after'     => $pool_num
        ];
        $send_gift = $all_group_user_fragment = [];
        $user_change_num = $all_expire_time = 0;
        $all_check_group = false;
        foreach ($fragment_group as $group) {
            $user_fragment_key = $this->cachePrefix. "fragment:{$user['user_id']}:{$group['id']}";
            //用户是否达到单个条件加入redis
            $check_group = false;
            foreach ($gifts as $gift) {
                if (in_array($gift['gift_template_id'], $group['gift_template_ids']) &&
                    !$this->redisObject->sismember($user_fragment_key, $gift['gift_template_id'])) {
                    $this->redisObject->sadd($user_fragment_key, $gift['gift_template_id']);
                    $all_check_group = $check_group = true;
                    if ($group['expire_time'] > 0) {
                        $all_expire_time = $group['expire_time'];
                        $this->redisObject->expire($user_fragment_key, $group['expire_time']);
                    }
                }
            }
            //用户是否完成该组全部条件 给用户发奖励
            $group_user_fragment = $this->redisObject->smembers($user_fragment_key);
            //全部集齐另加判断
            /*$all_group_user_fragment = array_merge($all_group_user_fragment, $group_user_fragment);
            if ($group['is_all']) {
                $group_user_fragment = $all_group_user_fragment;
                $check_group = true;
            }*/

            if ($check_group && $group['gift_template_ids'] === array_intersect($group['gift_template_ids'], $group_user_fragment)) {
                $now_num = $this->redisObject->get($fragment_pool_num_key);
                $now_fragment_num   = floor($now_num * $group['rate'] / 100);
                $now_fragment_num   = ($now_fragment_num > $fragment_max_share ? $fragment_max_share : $now_fragment_num);

                if($now_fragment_num > 0) {
                    $pool_num = $this->redisObject->decrby($fragment_pool_num_key, $now_fragment_num);
                    $o_str = '';
                    if ($group['is_all']) {
                        $is_all = 1;
                        $o_str = '全部';
                    }
                    $userRecordData = [
                        'user_id'           => $user['user_id'],
                        'change_num'        => $now_fragment_num,
                        'num_before'        => 0,
                        'num_after'         => 0,
                        'fragment_group_id' => $group['id'],
                        'send_gift_id'      => $poolConfig['send_gift_id'],
                        'desc'              => "仅记录：获得{$now_fragment_num}".$o_str,
                    ];
                    $userRecordInsertId = $this->fragmentUserRecordModel->insertGetId($userRecordData);
                    if (!$userRecordInsertId) {
                        throw new BasicException(-1, '抽奖---碎片错误');
                    }
                    app('model_gift_backpack')->addGift((int)$user['user_id'], (int)$poolConfig['send_gift_id'], (int)$now_fragment_num);

                    $poolRecordData[]   = [
                        'relation_id'   => $userRecordInsertId,
                        'change_num'    => -$now_fragment_num,
                        'num_before'    => $now_num,
                        'num_after'     => $pool_num,
                    ];
                    $user_change_num += $now_fragment_num;//用户在这次中获取的碎片总数
                    $send_gift = array_merge($poolConfig['send_gift'], ['count' => $user_change_num]);
                }
            }

        }
        $match = $this->cachePrefix."fragment:{$user['user_id']}:*";
        //更新倒计时
        if ($all_check_group && $all_expire_time > 0) {
            $this->cursorRedisKey($match, 2, $all_expire_time);
        }
        if ($is_all) {
            $this->cursorRedisKey($match, 1);
        }

        $fragmentPoolInfo->nums = $pool_num;
        $poolUpdateRes       = $fragmentPoolInfo->save();
        $poolRecordInsertRes = $this->fragmentPoolRecordModel::query()->insert($poolRecordData);

        if (!$poolUpdateRes && !$poolRecordInsertRes) {
            throw new BasicException(-1, '抽奖--碎片错误');
        }
        $user_fragment_data = [];
        if ($user_change_num) {
            $roomId = RedisService::getUserInRoom($user['user_id']);
            $roomName = RedisService::getRoomDetailByRoomId($roomId, 'room_name');
            $nickName = RedisService::getUserBaseInfo($user['user_id'], 'nickname', true);
            $user_fragment_data = [
                'user_id' => $user['user_id'],
                'room_name' => $roomName ?? '',
                'nickname' => $nickName,
                'user_change_num' => $user_change_num,
            ];
            $pushData = [
                'data' => $user_fragment_data,
                'bg_type' => $this->privateKey,
                'show_grade' => $this->showBroadcastGrade(),
            ];
            (new PushService(0, $roomId))->fragmentPush($pushData);
        }

        return [
            'send_gift' => $send_gift,
            'user_fragment_data' => $user_fragment_data ?: null,
        ];

    }

}
